/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-15 12:09:16
 * @LastEditTime: 2019-09-17 18:32:57
 * @LastEditors: Please set LastEditors
 */
// 引入mysql的配置文件
const db = require('../config/db');

// 引入sequelize对象
const Sequelize = db.sequelize;

// 引入数据表模型
const Article = Sequelize.import('../schema/article');
const User = Sequelize.import('../schema/user');
const Article_Love = Sequelize.import('../schema/article_love')

Article.sync({
    force: false,
    logging: false
}); //自动创建表
User.sync({
    force: false,
    logging: false
}); //自动创建表
Article_Love.sync({
    force: false,
    logging: false
}); //自动创建表

Article.belongsTo(User, {
    as: 'artuser',
    foreignKey: 'owner',
    targetKey: 'id'
});

Article.belongsTo(Article_Love, {
    as: 'love',
    foreignKey: 'id',
    targetKey: 'articleId'
});

Article_Love.belongsTo(Article, {
    as: 'loveArt',
    foreignKey: 'articleId',
    targetKey: 'id'
});



class ArticleModel {
    /**
     * 创建文章模型
     * @param data
     * @returns createArticle
     */
    static async createArticle(data) {
        console.log(data)
        return await Article.create({
            article: data.article,
            owner: data.owner,
            ishow: '1',
            islock: '1',
            iclass: data.iclass,
            imoshi: data.imoshi,
            ijianjie: data.ijianjie,
            igaiyao: data.igaiyao,
            ititle: data.ititle,
            isee: 0,
            artid: data.artid
        });
    }

    /**
     * @description: 审核中的文章
     * @param {owner} 
     * @return: 
     */
    static async myArticleCounts(data) {
        return await Article.findAll({
            where: {
                islock: '1',
                owner: data.owner
            }
        })
    }
    /**
     * @description: 阅读文章
     * @param id 
     * @return: readArtcile
     */
    static async readArtcile(id) {
        return await Article.findOne({
            where: {
                id
            },
            include: [{ // include关键字表示关联查询
                model: User, // 指定关联的model
                as: 'artuser', // 由于前面建立映射关系时为class表起了别名，那么这里也要与前面保持一致，否则会报错
                attributes: ['nickname', 'avatar'], // 这里的attributes属性表示查询class表的name和rank字段，其中对name字段起了别名className
            }],
        })
    }

    /**
     * @description: 增加阅读量
     * @param id 
     * @return: artcileIsee
     */
    static async artcileIsee(id) {
        return await Article.update({
            isee: Sequelize.literal('`isee` +1')
        }, {
            where: {
                id
            }
        })
    }

    /**
     * @description: 文章列表
     * @param {type} 
     * @return: 
     */
    static async articleList(page, userId) {
        return await Article.findAll({
            row: false,
            attributes: ['id', 'owner', 'ishow', 'islock', 'iclass', 'imoshi', 'ijianjie', 'igaiyao', 'ititle', 'isee', 'artid', 'createdAt', 'updatedAt'],
            where: {
                ishow: '1',
                islock: '0'
            },
            limit: 10,
            offset: page * 10,
            include: [{ // include关键字表示关联查询
                    model: User, // 指定关联的model
                    as: 'artuser', // 由于前面建立映射关系时为class表起了别名，那么这里也要与前面保持一致，否则会报错
                    attributes: ['nickname', 'avatar'],
                    required: false,
                },
                { // include关键字表示关联查询
                    model: Article_Love, // 指定关联的model
                    as: 'love', // 由于前面建立映射关系时为class表起了别名，那么这里也要与前面保持一致，否则会报错
                    attributes: ['userId'],
                    where: {
                        userId: userId,
                    },
                    required: false,
                }
            ],
            order: [
                ['updatedAt', 'DESC']
            ]
        })
    }

    /**
     * @description: 文章数目
     * @param null 
     * @return: articleCount
     */
    static async articleCount() {
        return await Article.count({
            where: {
                ishow: '1',
                islock: '0'
            },
        })
    }

    /**
     * @description: 收藏文章
     * @param {data} 
     * @return: 
     */
    static async articleLove(data) {
        return Sequelize.transaction(function (t) {
            return Article_Love.create({
                userId: data.userId,
                articleId: data.articleId,
                isDel: '0'
            }, {
                transaction: t
            }).then(function (data) {
                return Article_Love.findOne({
                    where: {
                        userId: data.userId,
                        articleId: data.articleId,
                        isDel: '0'
                    }
                })
            })

        }).then(function (result) {
            // 事务已被提交
            // result 是 promise 链返回到事务回调的结果
            return result;
        }).catch(function (err) {
            // 事务已被回滚
            // err 是拒绝 promise 链返回到事务回调的错误
        });
    }

    /**
     * @description: 查询收藏
     * @param {data} 
     * @return: 
     */
    static async findLove(data) {
        return await Article_Love.findOne({
            where: {
                userId: data.userId,
                articleId: data.articleId,
            }
        })
    }

    /**
     * @description: 删除收藏
     * @param {data} 
     * @return: 
     */
    static async deleteLove(data) {
        return await Article_Love.destroy({
            where: {
                userId: data.userId,
                articleId: data.articleId,
            }
        })
    }

    /**
     * @description: 查询我的所有收藏
     * @param {data} 
     * @return: 
     */
    static async findMyAllLove(data) {
        return await Article_Love.findAll({
            where: {
                userId: data.userId,
            },
            include: [{
                model: Article,
                as: "loveArt",
                attributes: ['id', 'ititle', 'ijianjie', 'iclass', 'imoshi', 'artId', 'isee', 'createdAt']
            }]
        })
    }

    /**
     * @description: 查询我的文章
     * @param {data} 
     * @return: 
     */
    static async getMyArticle(data) {
        return await Article.findAll({
            attributes: ['id', 'ititle', 'ijianjie', 'iclass','imoshi', 'createdAt', 'islock'],
            where: {
                owner: data.userId,
            },
            order: [
                ['createdAt', 'DESC']
            ]
        })
    }

    /**
     * @description: 查询我的文章列表
     * @param {data} 
     * @return: 
     */
    static async getMyArticleList(data) {
        return await Article.findAll({
            attributes: ['id', 'ititle', 'islock','imoshi'],
            where: {
                owner: data.userId,
            },
            order: [
                ['createdAt', 'DESC']
            ]
        })
    }

    /**
     * @description: 查询我的文章内容
     * @param {data} 
     * @return: 
     */
    static async getMyArticleMain(data) {
        return await Article.findOne({
            where: {
                id: data.artId,
            },
        })
    }

    /**
     * @description: 更新我的文章内容
     * @param {data} 
     * @return: 
     */
    static async updateMyArticle(data) {
        return await Article.update({
            article: data.article,
            iclass: data.iclass,
            imoshi: data.imoshi,
            ijianjie: data.ijianjie,
            igaiyao: data.igaiyao,
            ititle: data.ititle,
            artid: data.artid
        }, {
            where: {
                id: data.id,
                owner: data.userId
            }
        })
    }


}

module.exports = ArticleModel;